package com.txby.dplus.common.utils.util;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 提供了针对easyui响应的相关工具类
 * 
 * @author Administrator
 *
 */
public class ResponseUtils {

    /**
     * 
     * @param result boolean 
     * @param data 返回数据
     * @return
     */
    public static String buildJson(boolean result,Object data) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("result", result);
        map.put("data", data);
        return toJSONString(map);
    }
    

    /**
     * easyui 后台对象转换为分页grid中所使用的json对象
     * @param list 包含数据
     * @param totalSize 总记录数
     * @return
     */
    public static String buildJson(List<?> list,Integer totalSize) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", totalSize);
        map.put("rows", list);
        return toJSONString(map);
    }

    /**
     * 将List转换为EasyUI中grid所使用的json对象
     * 
     * @param list
     * @return json字符串
     */
    public static String buildJson(List<?> list) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", list.size());
        map.put("rows", list);
        return toJSONString(map);
    }

    /**
     * 把List数据转换为easyui中treegrid所使用的json数据, 根据数据自动构建父子关系 <br>
     * 适用于EasyUI的TreeGrid
     * 
     * @param list
     *            构建用的数据集合
     * @param idProperty
     *            数据对象表示主键的属性
     * @param parentIdProperty
     *            用于表示父节点id的属性
     * @param rootValue
     *            根节点中parentIdProperty的值
     * @return json字符串
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    public static <T> String buildTreeJson(List<?> list, String idProperty, String parentIdProperty, T rootValue) throws IllegalAccessException,
            InvocationTargetException, NoSuchMethodException {
        JSONArray array = buildTree(list, idProperty, parentIdProperty, rootValue);
        return toJSONString(array);

    }

    private static <T> JSONArray buildTree(List<?> list, String idProperty, String parentIdProperty, T parentValue) throws IllegalAccessException,
            InvocationTargetException, NoSuchMethodException {
        JSONArray array = new JSONArray();
        for (Object obj : list) {
            @SuppressWarnings("unchecked")
            T parentId = (T) BeanUtils.getProperty(obj, parentIdProperty);
            if (parentId == parentValue || (parentId != null && parentId.equals(parentValue))) {
                @SuppressWarnings("unchecked")
                T id = (T) BeanUtils.getProperty(obj, idProperty);
                JSONObject jsonObj = JSON.parseObject(toJSONString(obj));
                JSONArray subarray = buildTree(list, idProperty, parentIdProperty, id);
                if (subarray.size() > 0)
                    jsonObj.put("children", subarray);
                array.add(jsonObj);
            }
        }
        return array;
    }

    /**
     * 把List数据转换为easyui中tree, combotree所使用的json数据, 根据数据自动构建父子关系 <br>
     * 适用于EasyUI的Tree, ComboTree
     * 
     * @param list
     *            构建用的数据集合
     * @param idProperty
     *            数据对象表示主键的属性
     * @param parentIdProperty
     *            用于表示父节点id的属性
     * @param textProperty
     *            在Tree中所显示的文字对应的属性
     * @param rootValue
     *            根节点中parentIdProperty的值
     * @return json字符串
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    public static <T> String buildTreeJson(List<?> list, String idProperty, String parentIdProperty, String textProperty, T rootValue)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        JSONArray array = buildTree(list, idProperty, parentIdProperty, textProperty, rootValue);
        return toJSONString(array);

    }

    private static <T> JSONArray buildTree(List<?> list, String idProperty, String parentIdProperty, String textProperty, T parentValue)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        JSONArray array = new JSONArray();
        for (Object obj : list) {
            @SuppressWarnings("unchecked")
            T parentId = (T) BeanUtils.getProperty(obj, parentIdProperty);
            if (parentId == parentValue || (parentId != null && parentId.equals(parentValue))) {
                @SuppressWarnings("unchecked")
                T id = (T) BeanUtils.getProperty(obj, idProperty);
                String text = BeanUtils.getSimpleProperty(obj, textProperty);
                JSONObject jsonObj = new JSONObject();
                jsonObj.put("id", id);
                jsonObj.put("text", text);
                JSONObject jsonAttri = JSON.parseObject(toJSONString(obj));
                jsonObj.put("attributes", jsonAttri);
                JSONArray subarray = buildTree(list, idProperty, parentIdProperty, textProperty, id);
                if (subarray.size() > 0)
                    jsonObj.put("children", subarray);
                array.add(jsonObj);
            }
        }
        return array;
    }

    /**
     * 将对象转换为json字符串
     * yyyy-MM-dd HH:mm:ss
     * @param object
     * @return json字符串
     */
    public static final String toJSONString(Object object) {
        SerializeWriter out = new SerializeWriter();
        try {
            JSONSerializer serializer = new JSONSerializer(out);
            serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
            serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);
            serializer.setDateFormat(DateUtils.YYYYMMDDHHMMSS_19);
//            serializer.getPropertyFilters().add(HibernatePropertyFilter.getInstance());
            serializer.write(object);
            return out.toString();
        } finally {
            out.close();
        }
    }

    /**
     * 返回json字符串，格式为 {result : true/false}
     * 
     * @param result
     *            结果成功与否
     * @return json字符串
     */
    public static String buildResultJson(Boolean result) {
        return buildResultJson(result, null);
    }

    /**
     * 返回json字符串，格式为 {result : true/false,message : ''}
     * 
     * @param result
     *            结果成功与否
     * @param message
     *            信息描述
     * @return json字符串
     */
    public static String buildResultJson(Boolean result, String message) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("result", result);
        jsonObj.put("message", message);
        return jsonObj.toJSONString();
    }

    /**
    * @param  result  结果成功与否
    * @param  message 信息描述
    * @param  url     需要放置的url
    * @author 作者 jacking 
    * @date 2016-10-8 下午1:11:34 
    * @return  json字符串
     */
    public static String buildResultJson(Boolean result, String message,String url) {
    	JSONObject jsonObj = new JSONObject();
    	jsonObj.put("result", result);
    	jsonObj.put("message", message);
    	jsonObj.put("url", url);
    	return jsonObj.toJSONString();
    }
    
    
    /**
     * 返回json字符串，格式为 {result : '自定义判断字符串',message : '自定义的消息提示'}
     * 
     * @param result
     *           自定义判断字符串
     * @param message
     *            信息描述
     * @return json字符串
     */
    public static String buildResultJson(String result, String message) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("result", result);
        jsonObj.put("message", message);
        return jsonObj.toJSONString();
    }
    
    /**
     * map转json字符串
     * 
     * @param map
     * @return json字符串
     */
    public static String buildResultJson(Map<String, Object> map) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.putAll(map);
        return jsonObj.toJSONString();
    }
    
    
    /**
     * 实体对象转json字符串
     * 
     * @param map
     * @return json字符串
     */
    public static String buildResultJson(Object obj) {
        return JSON.toJSONString(obj);
    }

}
